<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="广告码" prop="adCode">
        <el-input
          v-model="queryParams.adCode"
          placeholder="请输入广告码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="1是视频2是文本" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择1是视频2是文本" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上下架" prop="adStatus">
        <el-select v-model="queryParams.adStatus" placeholder="请选择上下架" clearable size="small">
          <el-option
            v-for="dict in adStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:ads:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:ads:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:ads:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:ads:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="adsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="广告码" align="center" prop="adCode"/>
      <el-table-column label="广告类型" align="center" prop="type" :formatter="typeFormat"/>
      <el-table-column label="上下架" align="center" prop="adStatus" :formatter="adStatusFormat"/>
      <el-table-column label="内容" align="center" prop="content"/>
      <el-table-column label="视频地址" :show-overflow-tooltip="true" align="center" prop="url"/>
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:ads:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:ads:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close='closeDialog' width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="广告码" prop="adCode">
          <el-input v-model="form.adCode" placeholder="不可人工输入广告码" readonly/>
        </el-form-item>
        <el-form-item label="选择广告类型">
          <el-radio-group v-model="form.type">
            <el-radio
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上下架">
          <el-radio-group v-model="form.adStatus">
            <el-radio
              v-for="dict in adStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="视频地址" prop="url" v-show="form.type==1">
          <el-row :gutter="10">
            <el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11">
              <el-upload
                class="upload-demo"
                drag
                :headers="videoUpload.headers"
                :action="videoUpload.url"
                :show-file-list="false"
                accept=".mp4,.mkv,.MKV,.av,.rmvb,.rm"
                :on-success="handleVideoSuccess"
                :before-upload="beforeUploadVideo"
                :on-progress="uploadVideoProcess">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-col>
            <el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11">

            </el-col>
          </el-row>
          <el-progress :stroke-width="10" class="progressType" v-if="videoFlag == true"
                       type="circle" :percentage="videoUploadPercent" style="margin-top:30px;">
          </el-progress>
        </el-form-item>
        <el-form-item label="播放视频" v-show="form.url!=null">
          <video id="myVideo" style=" width: 100%;height: 280px;" 
                 v-if="this.form.url !='' && !videoFlag" :src="this.form.url" class="avatar video-avatar"
                 controls="controls">
            您的浏览器不支持视频播放
          </video>
        </el-form-item>
        <el-form-item label="上传地址" prop="url">
          <el-input v-model="this.form.type==1?this.form.url:this.form.url=null" type="textarea" placeholder="上传地址" readonly/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listAds, getAds, delAds, addAds, updateAds, exportAds} from "@/api/content/ads";
  import {getToken} from '@/utils/auth'

  export default {
    name: "Ads",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 广告管理表格数据
        adsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 1是视频2是文本字典
        typeOptions: 1,
        // 1上架0是下架字典
        adStatusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          adCode: undefined,
          type: undefined,
          adStatus: undefined,
          content: undefined,
          url: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        uploadUrl: "",//你要上传视频到你后台的地址
        videoFlag: false, //是否显示进度条
        videoUploadPercent: "", //进度条的进度，
        isShowUploadVideo: false, //显示上传按钮，
        videoUpload: {
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/sys/file/upload",
          url2: process.env.VUE_APP_BASE_API,
        },
      };
    },
    created() {
      this.getList();
      this.getDicts("sys_ads_type").then(response => {
        this.typeOptions = response.data;
      });
      this.getDicts("sys_on_status").then(response => {
        this.adStatusOptions = response.data;
      });
    },
    methods: {
      /** 查询广告管理列表 */
      getList() {
        this.loading = true;
        listAds(this.queryParams).then(response => {
          this.adsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 1是视频2是文本字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.type);
      },
      // 1上架0是下架字典翻译
      adStatusFormat(row, column) {
        return this.selectDictLabel(this.adStatusOptions, row.adStatus);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          adCode: undefined,
          type: "0",
          createTime: undefined,
          adStatus: "0",
          content: undefined,
          url: undefined
        };
        this.videoFlag = false;
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加广告管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getAds(id).then(response => {
          this.form = response.data;
          console.log( response.data)
          this.videoFlag  = false;
          this.open = true;
          this.title = "修改广告管理";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateAds(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addAds(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除广告管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delAds(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有广告管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportAds(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      },
      //上传成功回调
      handleVideoSuccess(res, file) {
        console.log("上传成功地址" + res)
        this.isShowUploadVideo = true;
        this.videoFlag = false;
        this.videoUploadPercent = 0;
        if (res != "") {
          this.showVideoPath = res;
          this.form.courseUrl = res;
          this.form.url = res;
          this.url = res;//上传返回地址
        } else {
          this.$message.error('视频上传失败，请重新上传！');
        }
      },
      //上传前回调
      beforeUploadVideo(file) {
        const isLt1024M = (file.size / 1024 / 1024) < 1024;
        this.form.videoSize = file.size / 1024 / 1024;
        //判断是不是MP4格式视频
        // if (['video/mp4'].indexOf(file.type) != 0) {
        //   this.$message.error('请上传正确的视频格式');
        //   return false;
        // }
        //单个视频大小限制在1024M以内
        if (!isLt1024M) {
          this.$message.error('上传视频大小不能超过1024MB哦!');
          return false;
        }
        this.isShowUploadVideo = false;
      },
      //进度条
      uploadVideoProcess(event, file, fileList) {
        this.videoFlag = true;
        this.videoUploadPercent = file.percentage.toFixed(0) * 1;
      },
      //关闭Dialog
      closeDialog(){
        this.reset();
        var myVideo = document.getElementById("myVideo");
        myVideo.pause()
      },
    }
  };
</script>

